/*
 * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */
package com.i360day.invoker;

import com.i360day.invoker.common.HttpInvokerRemoteConstant;
import com.i360day.invoker.http.Request;
import com.i360day.invoker.http.Response;
import com.i360day.invoker.socket.handler.ReplyMessageListener;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.management.openmbean.InvalidKeyException;
import java.io.ByteArrayInputStream;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author liju.z
 * @date 2024/3/26 21:10
 */
public class DefaultMessageReply implements ReplyMessageListener {
    private final MessagePendingReply<byte[]> messagePendingReply = new MessagePendingReply<>();
    private String replyTo;
    private Lock lock;

    public DefaultMessageReply(String replyTo) {
        this.replyTo = replyTo;
        this.lock = new ReentrantLock();
    }

    public String getReplyTo() {
        return replyTo;
    }

    @Override
    public void onMessage(byte[] replyMessage) {
        try {
            WebSocketResponse response = HttpInvokerRemoteConstant.objectMapper.readValue(replyMessage, WebSocketResponse.class);
            if (response.getId().equals(getReplyTo())) {
                messagePendingReply.reply(response.getBody());
            } else {
                messagePendingReply.completeExceptionally(new InvalidKeyException("id error"));
            }
        } catch (Exception ex) {
            messagePendingReply.returned(ex);
        }
    }

    public Response getResponse(Request request, int timeout, TimeUnit timeUnit) {
        try {
            byte[] bytes = messagePendingReply.get(timeout, timeUnit);

            return Response.Builder.create()
                    .body(new ByteArrayInputStream(bytes))
                    .status(bytes != null ? HttpStatus.OK.value() : HttpStatus.INTERNAL_SERVER_ERROR.value())
                    .setContextType(MediaType.APPLICATION_JSON_VALUE)
                    .request(request)
                    .build();
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
    }
}
